//模块就需要定义

define("register", ["jquery", "md5", "jquery.validate", "jquery.idcode"], function($){
	
	return {
		init : function(){
			
			//使用验证码
			
			$.idcode.setCode();   //加载生成验证码方法
			
			//用户名
			$.validator.addMethod("checkUname", function(val, ele){
				var reg = /^[a-zA-Z]+/;
				return reg.test(val);
				
			}, "用户名不合法");
			
			$uname = $("[name=uname]").val();
		
			
			//
			$("form").validate({
				//rules
				rules : {
				
					uname : {
						required : true,
						checkUname : true,
						rangelength : [6, 16],
						remote : {
							url : "./../server/isExistUser.php",
							type : "post",
							data : {"unameA" : function(){
									return $("[name=uname]").val();}}
						}
						
					},
					upwd : {
						required : true,
						rangelength : [6, 20]
					},
					upwd2 : {
						equalTo : "#upwd"
					},
					uemail : {
						required : true,
						email : true
					},
					Txtidcode : {
						required : true,
					}
				},
				//messages
				messages : {
					utel:{
						required:"手机号必填",
						rangelength:"请输入1开头的11位手机号",
					},
					uname : {
						required : "用户名必填",
						rangelength : "用户名必须是{0}到{1}之间",
						remote : "该用户名已经存在!"
					},
					upwd : {
						required : "密码必填",
						rangelength : "密码必须是{0}到{1}之间"
					},
					upwd2 : {
						equalTo : "2次密码不一致"
					},
					uemail : {
						required : "邮箱必填",
						email : "邮箱格式不合法"
					},
					Txtidcode : {
						required : "",
					}
				},
				//submitHandler
				submitHandler : function(){
					
					if($("[name=ufile]")[0].files.length<=0){
						alert("请选择头像");
						return false;
					}
					
					var IsBy = $.idcode.validateCode();  //调用返回值，返回值结果为true或者false
					if(IsBy){
						
						var formdata = new FormData();
						var $dataArr = $("form").serializeArray();
						
						$dataArr.forEach((ele, index) =>{
							// ele == {name: "uname", value: "admin11111"}
							
							if(ele.name != "Txtidcode" || ele.name != "upwd2"){
								
								if(ele.name=="upwd"){
									formdata.append(ele.name,$.md5(ele.value));
								}else{
									formdata.append(ele.name, ele.value);
								}
							}
						});
						formdata.append("ufile", $("[name=ufile]")[0].files[0]);
						
						
						
						$.ajax({
							type : "post",
							url : "./../server/register.php",
							data : formdata,
							processData:false,
							contentType:false,
							success:function(res){
								console.log(res);
							}
						})
						
						return false;
						
					} else {
						alert("请重新输入")
					}
					
					return false;
				}
			})
		},
		//图片预览功能
		preView : function(){
			$("[type=file]").on("change", function(){
				var read = new FileReader();
				read.readAsDataURL(this.files[0]);
				read.onload = function(ev){
					$("#head").attr("src", read.result);
				}
			})
			
		}
	}
})